package com.aqadoos;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Sample controller for going to the home page with a message
 */
@Controller
public class DepartmentController {

	private static final Logger logger = LoggerFactory
			.getLogger(DepartmentController.class);


	/**
	 * Selects the home page and populates the model with a message
	 */
	@RequestMapping(value = "/dept", method = RequestMethod.GET)
	public String dept() {
		return "dept";
	}
	
	@RequestMapping(value="/dept/getAll", method=RequestMethod.GET)
	public @ResponseBody String getAll() {
		logger.info("Getting all departments!");
        return getAllDepartments();
	}

    private String getAllDepartments() {
        Client client = Client.create();
        WebResource webResource = client
                .resource("http://localhost:9090/spring-mvc/rest/dept/findAll");
        String response = webResource.type("application/json").get(String.class);
        return new JSONDeserializer<String>().deserialize(response);
    }

    @RequestMapping(value="/dept/create", method=RequestMethod.POST)
    public @ResponseBody String create(@RequestParam String name) {
        Client client = Client.create();

        WebResource webResource = client
                .resource("http://localhost:9090/spring-mvc/rest/dept/create");

        String input = "{\"name\":\"" + name + "\"}";

        ClientResponse response = webResource.type("application/json")
                .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }
        return "{result:'success'}";        
    }
}
